/*
 * Copyright (C) 2011 Evgeniy Egorov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * FServicePriority.java
 *
 * Created on Oct 10, 2011, 10:21:13 AM
 */
package ru.apertum.qsystem.client.forms;

import lombok.extern.log4j.Log4j2;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;
import ru.apertum.qsystem.QSystem;
import ru.apertum.qsystem.client.model.FlexPriorityCell;
import ru.apertum.qsystem.client.model.FlexPriorityMableModel;
import ru.apertum.qsystem.common.NetCommander;
import ru.apertum.qsystem.common.Uses;
import ru.apertum.qsystem.common.cmd.RpcGetSelfSituation.SelfService;
import ru.apertum.qsystem.common.cmd.RpcGetSelfSituation.SelfSituation;
import ru.apertum.qsystem.common.model.INetProperty;

import javax.swing.DefaultCellEditor;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.LayoutStyle;
import javax.swing.border.MatteBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import java.awt.Color;
import java.util.HashMap;
import java.util.ResourceBundle;

/**
 * Диалог. Редактируем приоритет услуги.
 *
 * @author Evgeniy Egorov
 */
@SuppressWarnings({"squid:S1192", "squid:S1172", "squid:S1450", "squid:S1604", "squid:S1161", "squid:MaximumInheritanceDepth"})
@Log4j2
public class FServicePriority extends javax.swing.JDialog {

    private static ResourceMap localeMap = null;

    /**
     * Сделано паблик чтоб отсюда брать названия приоритетов услуг.
     *
     * @param key какой требуется текст
     * @return локализованный текст
     */
    public static String getLocaleMessage(String key) {
        if (localeMap == null) {
            localeMap = Application.getInstance(QSystem.class).getContext().getResourceMap(FServicePriority.class);
        }
        return localeMap.getString(key);
    }

    /**
     * Используемая ссылка на диалоговое окно.
     */
    private static FServicePriority dialog;

    /**
     * Creates new form FServicePriority.
     */
    public FServicePriority(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /**
     * Показать список обрабатываемых услуг с возможностью менять им приоритеты.
     *
     * @param netProperty свойства коннекта
     * @param owner       для модальности
     * @param plan        список обрабатываемых услуг
     * @param userId      юзер.
     */
    public static void show(INetProperty netProperty, JFrame owner, SelfSituation plan, Long userId) {
        log.info("Диалог управления приоритетами.");
        if (dialog == null) {
            dialog = new FServicePriority(owner, true);
        }
        dialog.fillPlan(plan);
        dialog.setLocation((owner.getLocation().x + owner.getWidth() / 2 - dialog.getWidth() / 2),
                (owner.getLocation().y + owner.getHeight() / 2 - dialog.getHeight() / 2));

        dialog.isUndo = true;
        dialog.netProperty = netProperty;
        dialog.userId = userId;
        dialog.setVisible(true);
        if (dialog.isUndo) {
            dialog.undo();
        }
    }

    private final HashMap<Long, Integer> oldValues = new HashMap<>();
    private boolean isUndo = true;
    private transient INetProperty netProperty;
    private Long userId;

    private void undo() {
        // вернем старые значения
        for (SelfService service : plan.getSelfservices()) {
            if (service.isFlexy() && oldValues.get(service.getId()) != null) {
                service.setPriority(oldValues.get(service.getId()));
            }
        }
    }

    private transient SelfSituation plan;

    /**
     * Выведем план в таьлицу.
     *
     * @param plan Выведем его.
     */
    public void fillPlan(SelfSituation plan) {
        this.plan = plan;
        // запомним старые значения на случай отката
        oldValues.clear();
        for (SelfService service : plan.getSelfservices()) {
            if (service.isFlexy()) {
                oldValues.put(service.getId(), service.getPriority());
            }
        }

        tablePlan.setModel(new FlexPriorityMableModel(plan));

        JComboBox<String> cb = new JComboBox<>();
        Uses.getCoeffWord().values().forEach(cb::addItem);
        TableCellEditor editor = new DefaultCellEditor(cb);
        TableColumnModel cm = tablePlan.getColumnModel();
        TableColumn tc = cm.getColumn(1);
        tc.setCellEditor(editor);

        tablePlan.setDefaultRenderer(SelfService.class, new FlexPriorityCell());
    }

    /**
     * команду на сервер для изменения текущих приоритетов. Изменения только текущие, ничего не сохранияется в БД
     */
    public void savePlan(INetProperty netProperty, Long userId) {
        final StringBuilder sb = new StringBuilder();
        for (SelfService service : plan.getSelfservices()) {
            if (service.isFlexy()) {
                sb.append(sb.length() == 0 ? "" : "&").append(service.getId()).append("=").append(service.getPriority());
            }
        }
        NetCommander.changeFlexPriority(netProperty, userId, sb.toString());
        sb.setLength(0);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    // Generated using JFormDesigner non-commercial license
    private void initComponents() {
        ResourceBundle bundle = ResourceBundle.getBundle("ru.apertum.qsystem.client.forms.resources.FServicePriority");
        jPanel1 = new JPanel();
        buttonExit = new JButton();
        buttonOK = new JButton();
        buttonApply = new JButton();
        jScrollPane1 = new JScrollPane();
        tablePlan = new JTable();

        //======== this ========
        setTitle(bundle.getString("Form.title"));
        setName("Form");
        var contentPane = getContentPane();

        //======== jPanel1 ========
        {
            jPanel1.setBorder(new MatteBorder(1, 1, 1, 1, Color.black));
            jPanel1.setName("jPanel1");

            //---- buttonExit ----
            buttonExit.setText(bundle.getString("buttonExit.text"));
            buttonExit.setName("buttonExit");
            buttonExit.addActionListener(e -> buttonExitActionPerformed(e));

            //---- buttonOK ----
            buttonOK.setText(bundle.getString("buttonOK.text"));
            buttonOK.setName("buttonOK");
            buttonOK.addActionListener(e -> buttonOKActionPerformed(e));

            //---- buttonApply ----
            buttonApply.setText(bundle.getString("buttonApply.text"));
            buttonApply.setName("buttonApply");
            buttonApply.addActionListener(e -> buttonApplyActionPerformed(e));

            GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                    jPanel1Layout.createParallelGroup()
                            .addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                    .addContainerGap(147, Short.MAX_VALUE)
                                    .addComponent(buttonOK, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(buttonApply)
                                    .addGap(18, 18, 18)
                                    .addComponent(buttonExit)
                                    .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                    jPanel1Layout.createParallelGroup()
                            .addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(jPanel1Layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                            .addComponent(buttonExit)
                                            .addComponent(buttonApply)
                                            .addComponent(buttonOK))
                                    .addContainerGap())
            );
        }

        //======== jScrollPane1 ========
        {
            jScrollPane1.setName("jScrollPane1");

            //---- tablePlan ----
            tablePlan.setModel(new DefaultTableModel(
                    new Object[][]{
                            {null, null, null, null},
                            {null, null, null, null},
                            {null, null, null, null},
                            {null, null, null, null},
                    },
                    new String[]{
                            "Title 1", "Title 2", "Title 3", "Title 4"
                    }
            ));
            tablePlan.setName("tablePlan");
            tablePlan.setRowSelectionAllowed(false);
            jScrollPane1.setViewportView(tablePlan);
        }

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
                contentPaneLayout.createParallelGroup()
                        .addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE)
        );
        contentPaneLayout.setVerticalGroup(
                contentPaneLayout.createParallelGroup()
                        .addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
                                .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );
        pack();
        setLocationRelativeTo(getOwner());
    }// </editor-fold>//GEN-END:initComponents

    private void buttonExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonExitActionPerformed
        isUndo = true;
        dialog.setVisible(false);
    }//GEN-LAST:event_buttonExitActionPerformed

    private void buttonApplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonApplyActionPerformed
        // сохраним изменения
        savePlan(netProperty, userId);
        // запомним старые значения на случай отката
        oldValues.clear();
        for (SelfService service : plan.getSelfservices()) {
            if (service.isFlexy()) {
                oldValues.put(service.getId(), service.getPriority());
            }
        }
        isUndo = true;
    }//GEN-LAST:event_buttonApplyActionPerformed

    private void buttonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonOKActionPerformed
        savePlan(netProperty, userId);
        isUndo = false;
        dialog.setVisible(false);
    }//GEN-LAST:event_buttonOKActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // Generated using JFormDesigner non-commercial license
    private JPanel jPanel1;
    private JButton buttonExit;
    private JButton buttonOK;
    private JButton buttonApply;
    private JScrollPane jScrollPane1;
    private JTable tablePlan;
    // End of variables declaration//GEN-END:variables
}
